use crate::{config::SEARCH_RESULT_FILE_NAME, models::Config};
use anyhow::Result;
use std::path::Path;
use std::process::Command;

/// 查看.search文件中的条目
pub fn view_entries(
    index: Option<usize>,
    open: Option<usize>,
    config: &Config,
    working_dir: &Path,
) -> Result<()> {
    let search_file = working_dir.join(SEARCH_RESULT_FILE_NAME);

    // 创建条目迭代器
    let mut entries = crate::entry::entries_iter(&search_file);

    if let Some(idx) = index {
        // 显示指定条目的详细信息
        if let Some(entry) = entries.nth(idx) {
            println!("{}", entry);
        }
    } else if let Some(idx) = open {
        // 打开指定条目对应的文件
        if let Some(entry) = entries.nth(idx) {
            open_file(&entry.file_path, &config.file_opener)?;
        }
    } else {
        // 显示所有条目
        for (i, entry) in entries.enumerate() {
            println!("{}: {}", i, entry.file_path);
        }
    }

    Ok(())
}

/// 使用配置的应用打开文件
fn open_file(file_path: &str, opener: &str) -> Result<()> {
    let status = Command::new(opener).arg(file_path).status()?;

    if !status.success() {
        log::error!(
            "Failed to open file '{}' with vim, exit status: {:?}",
            file_path,
            status
        );
        anyhow::bail!("Failed to open file with vim");
    }

    Ok(())
}
